package com.encrypt;

import com.encrypt.util.ByteToString;

import java.security.MessageDigest;

/**
 * Created by huangyugen on 2019/04/28
 * 基于MD4算法实现，不同之处在于摘要长度更长，更安全
 **/
public class SHACoder {

    public final static String SHA = "SHA";
    public final static String SHA_256 = "SHA-256";
    public final static String SHA_384 = "SHA-384";
    public final static String SHA_512 = "SHA-512";



    /**
     * sha加密算法
     * @param originString
     * @param sha
     * @return
     */
    public static String encodeBySHA(String originString,String sha){
        if (originString != null){
            try{
                //创建具有指定算法名称的信息摘要
                MessageDigest md = MessageDigest.getInstance(sha);
                //使用指定的字节数组对摘要进行最后更新，然后完成摘要计算
                byte[] results = md.digest(originString.getBytes());
                //将得到的字节数组变成字符串返回
                String resultString = ByteToString.byteArrayToHexString(results);
                return resultString;
            } catch(Exception ex){
                ex.printStackTrace();
            }
        }
        return null;
    }


    public static void main(String[] args) {
        String data = "Java加密与解密的艺术";
        System.out.println("【原 文】："+data);
        System.out.println("【编码后】："+SHA+"     -->"+SHACoder.encodeBySHA(data,SHA));
        System.out.println("【编码后】："+SHA_256+" -->"+SHACoder.encodeBySHA(data,SHA_256));
        System.out.println("【编码后】："+SHA_384+" -->"+SHACoder.encodeBySHA(data,SHA_384));
        System.out.println("【编码后】："+SHA_512+" -->"+SHACoder.encodeBySHA(data,SHA_512));
    }

}
